package jdbc;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * Statement对象是用来执行SQL语句的,而针对不同类型的SQL语句使用方法不一样
 * 执行DDL,DML语句,executeUpdate方法
 * 执行DQL语句,使用ResultSet对象的executeQuery方法
 */
public class StatementDemo {
    public static void main(String[] args) {

    }
    /**
     * 执行DML语句
     */
    @Test
    public void testDML() throws Exception {
        //1.注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.获取连接
        String url = "jdbc:mysql:///db1?useSSL=false";
        String userName = "root";
        String password = "123456";
        Connection con = DriverManager.getConnection(url,userName,password);
        //3.定义sql语句
        String sql = "update account set money = 3000 where id = 1";
        //4.获取执行语句的statement对象
        Statement stmt = con.createStatement();
        //5.执行sql
        int count = stmt.executeUpdate(sql);
        //6.处理结果
        System.out.println(count);
        if(count>0) System.out.println("修改成功!");
        else System.out.println("修改失败~");
        //7.释放资源
        stmt.close();
        con.close();
    }

    /**
     * 执行DDL语句
     */
    @Test
    public void testDDL() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql:///db1?useSSL=false";
        String userName = "root";
        String password = "123456";
        Connection con = DriverManager.getConnection(url,userName,password);

        String sql = "drop database if exists db2";
        Statement stmt = con.createStatement();

        int count = stmt.executeUpdate(sql);
        System.out.println(count);

        //7.释放资源
        stmt.close();
        con.close();
    }

    /**
     * ResultSet对象是为了接复杂的查询语句返回值
     * 提供方法next将光标前移动一行并判断是否为有效行
     * 数据类型 getXxx(参数)获取数据,参数可以使int和String分别对应表头名
     */
    /**
     * 执行DQL语句
     */
    @Test
    public void testResultSet() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql:///db1?useSSL=false";
        String userName = "root";
        String password = "123456";
        Connection con = DriverManager.getConnection(url,userName,password);

        String sql = "select id,name,money from account";
        Statement stmt = con.createStatement();

        ResultSet rs = stmt.executeQuery(sql);
        //最开始rs的光标是指在表头的,我们需要逐行判断
        while(rs.next()){
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String money = rs.getString("money");

            System.out.println(id + name + money);
        }

        //7.释放资源
        rs.close();
        stmt.close();
        con.close();
    }
}
